package com.wbpay.sdk.pay.wxplugin;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.wbpay.sdk.constant.Constants;
import com.wbpay.sdk.framework.IPayFunction;
import com.wbpay.sdk.framework.PayResult;
import com.wbpay.sdk.model.SdkInfo;
import com.wbpay.sdk.params.PayParams;
import com.wbpay.sdk.pay.IPay;
import com.wbpay.sdk.utils.Log;
import com.wbpay.sdk.utils.Utils;

/**
 * 微信支付模块
 */
public class WxPluginPay implements IPay {

    private Context mContext;
    private IPayFunction mPayFunction;

    @Override
    public void init(Context context, IPayFunction f) {
        mContext = context;
        mPayFunction = f;
    }

    @Override
    public void pay(PayParams payParams) {
        payByWxPlugin(payParams);
    }

    /**
     * 请求支付插件进行支付
     */
    private void payByWxPlugin(PayParams payParams) {
        if (payParams == null) {
            String desc = mContext.getString(Utils.getStringId(mContext, "jy_null_payparams"));
            mPayFunction.notifyPayResult(PayResult.PAY_FAILURE, desc, this);
            return;
        }
        String broadcastAction = setupAndGetBroadcast();
        Intent intent = new Intent("com.wbpay.pay.intent.action.WXPAY");
        intent.putExtra("server", payParams.getServer());
        intent.putExtra("price", payParams.getPrice());
        intent.putExtra("attach", payParams.getAttach());
        /**
         * 商品描述交易字段格式根据不同的应用场景按照以下格式：
         * APP——需传入应用市场上的APP名字-实际商品名称，天天爱消除-游戏充值。
         */
        intent.putExtra("subject", payParams.getSubject());
        /**
         * 商户系统内部订单号，要求32个字符内，只能是数字、大小写字母_-|*@ ，且在同一个商户号下唯一。详见商户订单号
         */
        intent.putExtra("order", payParams.getOrder());
        intent.putExtra("body", payParams.getBody());
        intent.putExtra("game", SdkInfo.get(mContext).getGame());
        intent.putExtra("package", mContext.getPackageName());
        intent.putExtra(Constants.EXTRA_CALLBACK, broadcastAction);
        intent.setPackage(Constants.WXPAY_PLUGIN_PKGNAME);
        try {
            mContext.startActivity(intent);
        } catch (Exception e) {
            if (mPayFunction != null) {
                String desc = mContext.getString(Utils.getStringId(mContext, "jy_not_install_wxpay"));
                mPayFunction.notifyPayResult(PayResult.PAY_FAILURE, desc, this);
            }
        }
    }

    @Override
    public String getPayName() {
        return mContext.getString(Utils.getStringId(mContext, "jy_pay_list_activity_wx_pay"));
    }

    @Override
    public int getPayType() {
        return PAY_TYPE_WXPLUGINPAY;
    }

    @Override
    public boolean checkPayAvailable() {
        if (!Utils.isInstalled(mContext, Constants.WX_PKGNAME)) {
            Log.e(Log.TAG, "微信未安装");
            return false;
        }
        return true;
    }

    @Override
    public int getPayIcon() {
        return Utils.getDrawableId(mContext, "jy_wx");
    }

    @Override
    public String getPayDesc() {
        return mContext.getString(Utils.getStringId(mContext, "jy_wxpluginpay_desc"));
    }

    @Override
    public String toString() {
        return getPayName();
    }

    /**
     * 设置微信支付回调广播
     *
     * @return
     */
    private String setupAndGetBroadcast() {
        try {
            // 注销之前注册的广播
            mContext.unregisterReceiver(mBroadcastReceiver);
        } catch (Exception e) {
        }
        String action = mContext.getPackageName() + ".intent.action.WXPAYRESULT";
        IntentFilter filter = new IntentFilter(action);
        mContext.registerReceiver(mBroadcastReceiver, filter, Constants.PERMISSION_WX_SEND_RESULT, null);
        return action;
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            mContext.unregisterReceiver(mBroadcastReceiver);
            int error = -1;
            String desc = null;
            if (intent != null) {
                error = intent.getIntExtra("RESULT_CODE", -1);
                desc = intent.getStringExtra("RESULT_DESC");
            }
            Log.d(Log.TAG, "error : " + error + " , desc : " + desc);
            processWxPayResult(error, desc);
        }
    };

    private void processWxPayResult(int error, String desc) {
        int payResult = PayResult.PAY_FAILURE;
        if (error == 0) {
            payResult = PayResult.PAY_SUCCESS;
        } else if (error == -1) {
            payResult = PayResult.PAY_FAILURE;
        } else if (error == -2) {
            payResult = PayResult.PAY_CANCEL;
        }
        if (mPayFunction != null) {
            mPayFunction.notifyPayResult(payResult, desc, this);
        }
    }
}
